package com.kk.loadimg;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URL;
import java.util.Objects;

/**
 * 客户端
 * 上传图片
 *
 * @author 王志强
 * @date 2021-12-02
 */
public class ImgClient {
    public ImgClient() {
        try {
            // 建立连接
            Socket socket = new Socket("127.0.0.1", 8888);

            //选择需要上传的图片
            URL resource = ImgClient.class.getClassLoader().getResource("imgs/a.jpg");

            //以文件输入流读取
            FileInputStream fileInputStream = new FileInputStream(Objects.requireNonNull(resource).getFile());

            //输出流上传
            OutputStream outputStream = socket.getOutputStream();
            byte[] buff = new byte[512];
            int len;

            //输入流读一次，上传一次
            while ((len = fileInputStream.read(buff)) != -1) {
                //上传
                outputStream.write(buff, 0, len);
                System.out.println("len = " + len);
            }

            System.out.println("上传成功！！");


/*          //获取响应结果
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int read = inputStream.read(bytes);*/


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ImgClient imgClient = new ImgClient();
        System.out.println(ImgClient.class.getClassLoader().getResource("imgs/a.jpg"));

    }
}
